/*
 *    This file is part of SSHTunneler.
 *
 *    Copyright 2009 Jean-Sebastien Gelinas <calestar@gmail.com>
 *
 *    SSHTunneler is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    SSHTunneler is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with SSHTunneler.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package sshtunneler.packager.installergenerator;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

import sshtunneler.packager.data.AdditionalFiles;
import sshtunneler.packager.data.Config;
import sshtunneler.packager.data.ScriptVariables;
import sshtunneler.packager.data.TunnelerConfig;
import sshtunneler.tools.Tool;

public class ScriptGenerator {

	public ScriptGenerator() {
	}

	public String generate_as_string() {
		StringBuffer s = new StringBuffer();

		/* Handle variables */
		for (String varname : ScriptVariables.inst.allVariables()) {
			if (!ScriptVariables.inst.is_native(varname)) {
				String value = ScriptVariables.inst.getVariableValue(varname);
				s.append("let " + varname + " = " + value + " \\n\\\n");
				s.append("mkdir $(" + varname + ")| \\n\\\n");
			}
		}

		s.append("copy SSHTunneler.jar => $(INSTALL_DIR) \\n\\\n");

		if (!TunnelerConfig.inst.isProg_update()) {
			if (!TunnelerConfig.inst.isOverwrite_all()) {
				s
						.append("backup $(USERHOME_DIR)|SSHTunneler_Default.tun \\n\\\n");
			}
			s.append("copy SSHTunneler_Default.tun => $(USERHOME_DIR) \\n\\\n");
		}

		/* Handle tools */
		for (Tool t : Config.inst.tools) {
			String tool_name = t.getClass().getName();
			s.append("copy tools|" + tool_name + " => $(TOOLS_DIR) \\n\\\n");
		}

		/* Handle additional files */
		for (File f : AdditionalFiles.inst.files()) {
			String file_name = f.getName();
			String dest = AdditionalFiles.inst.destination_for(f);
			s.append("copy " + file_name + " => " + dest + " \\n\\\n");
		}

		s.append("\n");
		return s.toString();
	}

	public void generate_to(File output) throws FileNotFoundException {
		PrintStream out = new PrintStream(output);
		out.print("script = \\\n");
		out.print(this.generate_as_string());
		out.close();
	}
}
